<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Models\Admin\Achievement;
use App\Models\Admin\AchievementOrderRefund;
use App\Models\Admin\AdminBonusLog;
use App\Models\Admin\AdminUser;
use App\Models\Admin\AfterSale;
use App\Models\User\UserBase;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AchievementOrderController extends BaseController
{
    private $field = [
        "orderSn" => "require", "customer_name" => "require", "customer_mobile" => "require", "we_account" => "",
        "refund_money" => 'require',"description" => 'require', 'pic_id' => 'require', "pay_mode" => 1, "status" => 1,
        "payer_name" => "require", "payer_account" => "require"
    ];
    private $fieldMsg = [
        "refund_sn" => "退款编号", "customer_name" => "客户名", "customer_mobile" => "客户手机号", "refund_money" => '退款金额',
        "description" => '退款说明', 'pic_id' => '图片', "payer_name" => "付款名称", "payer_account" => "付款账号"
    ];
    public function __construct(Request $request){
        parent::__construct($request);
    }

    // 列表
    public function getDataList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $page = $request->page_no ? : 1;
        $pageSize = $request->page_size ?: 10;

        $db = AchievementOrderRefund::query()->from(AchievementOrderRefund::query()->getModel()->getTable()." as aor")
            ->leftJoin(AdminUser::query()->getModel()->getTable()." as au", "au.id", "=", "aor.admin_id")
            ->leftJoin(AdminUser::query()->getModel()->getTable()." as aus", "aus.id", "=", "aor.verify_id")
            ->where("aor.mall_id", $request->mallId);
        if($request->refundSn){
            $db->where('aor.refund_sn', "=", $request->refundSn);
        }
        if($this->AU['position'] != "超级管理员") {
            $adminUserModel = new UserBase();
            $user_list = $adminUserModel->getAdminSubuser($this->AU['id']);
            $db->whereIn("admin_id", $user_list);
        }
        $this->returnData['data'] = [
            "total" => $db->count(),
            "rows" => $db->select([
                "au.name as admin_name", "aus.name as verify_name", "aor.id", "aor.admin_id", "aor.refund_sn", "aor.customer_name", "aor.customer_mobile", "aor.is_pay",
                "aor.goods_name", "aor.total_money", "aor.refund_money", "aor.verify_id", "aor.status", "aor.buy_time", "aor.refund_time", "aor.create_time",
                "aor.achievement_money", "aor.commission_money", "aor.bonus_money"
            ])->skip(($page - 1) * $pageSize)->take($pageSize)
                ->orderBy("create_time", "desc")
                ->get()->toArray()
        ];
        return $this->return_result($this->returnData);
    }

    // 业绩详情
    public function getAchievementDetail(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if($request->orderSn){
            $db = Achievement::query()->where("number_sn", $request->orderSn)
                ->where("mall_id", $request->mallData['id']);
            if($this->AU['position'] != "超级管理员"){
                $adminUserModel = new UserBase();
                $userList = $adminUserModel->getAdminSubuser($this->AU['id']);
                $db->whereIn("admin_users_id", $userList);
            }
            $field = ["member_name", "member_phone", "goods_money", "order_bonus", "goods_name", "buy_time", "number_sn", "id", "refund_status", 'status', 'sale_bonus', 'buy_length'];
            $data = $db->select($field)->first();
            if(!empty($data)){
                $data = $data->toArray();
                if($data['status'] == '0'){
                    return ErrorCode::code("customized", "订单正在审核中无法退款");
                }
                if($data['status'] != '1'){
                    return ErrorCode::code("customized", "订单已被拒绝无法退款");
                }
                if($data['refund_status'] != 0){
                    return ErrorCode::code("customized", "订单".($data['refund_status'] == '1' ? "已退款" : "已部分退款"));
                }
                $data['bonus_money'] = sprintf('%.2f', $data['sale_bonus'] ?: 0);
                $time = AfterSale::query()->where(["number_sn" => $request->orderSn, "mall_id" => $request->mallData['id']])->sum("after_time");
                $data['serverTime'] = "{$time}（{$data['buy_length']}）";
                $this->returnData['data'] = $data;
            }
        }
        return $this->return_result($this->returnData);
    }

    // 退款详情
    public function getDetail(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return ErrorCode::code("params_not_exist", "退款单ID");
        }
        $data = AchievementOrderRefund::query()->from(AchievementOrderRefund::query()->getModel()->getTable()." as aor")
            ->leftJoin(AdminUser::query()->getModel()->getTable()." as au", "au.id", "=", "aor.admin_id")
            ->leftJoin(AdminUser::query()->getModel()->getTable()." as aus", "aus.id", "=", "aor.verify_id")
            ->where("aor.id", $request->id)
            ->select(["au.name as admin_name", "aus.name as verify_name", "aor.*"])
            ->first();
        if(!empty($data)){
            $data = $data->toArray();
            foreach ((array)explode(",", $data['pic_id']) as $url){
                $data['pic_url'][] = $this->processingPictures($url);
            }
            $data['pay_pic_url'] = $this->processingPictures($data['pay_pic_id']);
            $time = AfterSale::query()->where(["number_sn" => $data['refund_sn'], "mall_id" => $request->mallData['id']])->sum("after_time");
            $totalTime = Achievement::query()->where(["number_sn" => $data['refund_sn'], "mall_id" => $request->mallData['id']])->value("buy_length");
            $data['orderInfo'] = [
                "number_sn" => $data['refund_sn'], "member_name" => $data['customer_name'], "member_phone" => $data['customer_mobile'], "goods_money" => $data['total_money'],
                "order_bonus" => $data['total_commission_money'], "goods_name" => $data['goods_name'], "buy_time" => $data['buy_time'], "bonus_money" => $data["total_bonus_money"],
                "serverTime" => "{$time}（{$totalTime}）"
            ];
        }else{
            $data = [];
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    // 添加
    public function toAdd(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data = [];
        foreach ($this->field as $k => $v) {
            if($v === 'require' && empty($request->$k)){
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            $data[$k] =  isset($request->$k) ? trim($request->$k) : $v;
        }
        $data['refund_sn'] = $data['orderSn'];
        unset($data['orderSn']);
        $achievementData = Achievement::query()->where(["number_sn" => $data['refund_sn'], "mall_id" => $request->mallData['id'], "status" => 1])
            ->select("goods_money", "goods_name", "buy_time", "order_bonus", 'sale_bonus')
            ->first();
        if(empty($achievementData)){
            return ErrorCode::code("customized", '业绩订单不存在');
        }
        if(AchievementOrderRefund::query()->where(['refund_sn' => $data['refund_sn'], "mall_id" => $request->mallData['id']])->whereNotIn("status", [3])->count()){
            return ErrorCode::code("customized", '业绩订单已提交退款了');
        }
        if($data["refund_money"] > $achievementData->goods_money){
            return ErrorCode::code("customized", '退款金额超过订单总金额');
        }
        $data = array_merge($data, [
            "mall_id" => $request->mallData['id'], "admin_id" => $this->AU['id'], "goods_name" => $achievementData->goods_name, "total_money" => $achievementData->goods_money,
            "total_commission_money" => $achievementData->order_bonus, "buy_time" => substr($achievementData->buy_time, 0, 10), "create_time" => Carbon::now(),
            "total_bonus_money" => $achievementData->sale_bonus
        ]);
        if(!AchievementOrderRefund::query()->insert($data)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = "提交退款失败";
        }
        return $this->return_result($this->returnData);
    }

    // 更新审核状态
    public function ajax(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return ErrorCode::code("params_not_exist", "退款单ID");
        }
        if(!$request->action){
            return ErrorCode::code("params_not_exist", "操作");
        }
        switch ($request->action){
            case "agree":
                if(!$request->remark){
                    return ErrorCode::code("params_not_exist", "审核备注");
                }
                if(!$request->achievement_money){
                    return ErrorCode::code("params_not_exist", "扣除业绩金额");
                }
                if(!$request->commission_money && $request->commission_money < 0){
                    return ErrorCode::code("params_not_exist", "扣除提成金额");
                }
                if(!$request->bonus_money && $request->bonus_money < 0){
                    return ErrorCode::code("params_not_exist", "扣除奖金金额");
                }
                $update = [
                    "verify_remark" => $request->remark, "achievement_money" => $request->achievement_money, "commission_money" => $request->commission_money,
                    "bonus_money" => $request->bonus_money, "status" => 2
                ];
                break;
            case "refuse":
                if(!$request->remark){
                    return ErrorCode::code("params_not_exist", "审核备注");
                }
                $update = ["verify_remark" => $request->remark, "status" => 3];
                break;
            default:
                return ErrorCode::$admin_enum['fail'];
                break;
        }
        $data = AchievementOrderRefund::query()->where("id", $request->id)->first();
        if(empty($data)){
            return ErrorCode::code("customized", '退款单不存在');
        }
        if($data->total_money < $request->achievement_money){
            return ErrorCode::code("customized", '扣除业绩金额不能超过总业绩');
        }
        if($data->total_commission_money < $request->commission_money){
            return ErrorCode::code("customized", '扣除提成金额不能超过总提成');
        }
        if($data->total_bonus_money < $request->bonus_money){
            return ErrorCode::code("customized", '扣除奖金金额不能超过总奖金');
        }
        $update['verify_id'] = $this->AU['id'];
        AchievementOrderRefund::query()->where("id", $request->id)->update($update);
        return $this->return_result($this->returnData);
    }

    // 提交付款记录
    public function getSubmitPay(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return ErrorCode::code("params_not_exist", "退款单ID");
        }
        if(!$request->remark){
            return ErrorCode::code("params_not_exist", "付款备注");
        }
        if(!$request->pic_id){
            return ErrorCode::code("params_not_exist", "付款图片");
        }
        $data = AchievementOrderRefund::query()->where("id", $request->id)->first();
        if(empty($data)){
            return ErrorCode::code("customized", '退款单不存在');
        }
        $achievement = Achievement::query()->where("number_sn", $data['refund_sn'])
            ->where("mall_id", $request->mallData['id'])
            ->where("status", 1)
            ->first();
        if(empty($achievement)){
            return ErrorCode::code("customized", '业绩单不存在');
        }
        $afterSaleData = AfterSale::query()->where("number_sn", $data['refund_sn'])
            ->where("mall_id", $request->mallData['id'])
            ->where("after_status", 0)
            ->first();
        $userId = !empty($afterSaleData) ? $afterSaleData->after_sale_id : $achievement->after_sale_id;
        DB::beginTransaction();
        try {
            $update = ["is_pay" => 2, "refund_time" => Carbon::now(), "payed_remark" => $request->remark, "pay_pic_id" => $request->pic_id];
            if (AchievementOrderRefund::query()->where("id", $request->id)->update($update)) {
                // 更新业绩单
                $achievementUpdate = [
                    "goods_money" => $achievement->goods_money - $data->achievement_money, // 减业绩
                    "order_bonus" => $achievement->order_bonus - $data->commission_money, // 减提成
                    "sale_bonus" => $achievement->sale_bonus - $data->bonus_money, // 减奖金
                ];
                $achievementUpdate['refund_status'] = $achievementUpdate['goods_money'] ? 2 : 1;
                if (!Achievement::query()->where("id", $achievement->id)->update($achievementUpdate)) {
                    DB::rollBack();
                    return ErrorCode::code("customized", '更新业绩单失败');
                }
                // 更新奖金
                if (!AdminUser::query()->where("id", $userId)->update(["sale_bonus" => DB::raw("sale_bonus-{$data->bonus_money}")])) {
                    DB::rollBack();
                    return ErrorCode::code("customized", '更新用户销售奖金失败');
                } else {
                    //业绩流水表
                    $data_ins['admin_users_id'] = $userId;
                    $data_ins['type'] = 9; // 减少奖金
                    $data_ins['money'] = -$data->bonus_money;
                    $data_ins['cur_bonus'] = AdminUser::query()->where("id", $userId)->value("sale_bonus");
                    $data_ins['member_name'] = $achievement->member_name;
                    $data_ins['member_phone'] = $achievement->member_phone;
                    $data_ins['goods_name'] = $achievement->goods_name;
                    $data_ins['goods_money'] = $achievement->goods_money;
                    $data_ins['order_number'] = $achievement->order_number;
                    $data_ins['number_sn'] = $achievement->number_sn;
                    $data_ins['remarks'] = $achievement->remarks;
                    $data_ins['submitter'] = AdminUser::query()->where("id", $userId)->value("name");
                    $data_ins['auditor'] = $this->AU['name'];
                    $data_ins["mall_id"] = request()->mallData["id"];
                    $adminBonusModel = new AdminBonusLog();
                    $adminBonusModel->adminBonusLogInsert($data_ins);
                }
                // 更新售后单
                if (!empty($afterSaleData->id) && !AfterSale::query()->where("id", $afterSaleData->id)->update(["bonus_royalty" => DB::raw("bonus_royalty-{$data->bonus_money}"), "after_status" => 1])) {
                    DB::rollBack();
                    return ErrorCode::code("customized", '更新售后单失败');
                }
            } else {
                DB::rollBack();
            }
        }catch (\Exception $e){
            DB::rollBack();
            return ErrorCode::code("customized", $e->getMessage());
        }
        DB::commit();
        return $this->return_result($this->returnData);
    }
}